<?php

namespace app\admin\model\booking;

use think\Model;
use app\admin\model\booking\House;

class Calendar extends Model
{

    // 表名
    protected $name = 'booking_calendar';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'day_time_text'
    ];

    public function getDayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['day_time']) ? $data['day_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 计算房间预订的日期价格
     *
     * @param int    $house_id
     * @param string $checkin_time
     * @param string $leave_time
     * @return int|string
     */
    public static function totalHousePrice($house_id, $checkin_time, $leave_time)
    {
        $startTime = strtotime($checkin_time);
        $endTime = strtotime($leave_time);
        $house = House::field('id,price')->where('status', 'up')->where('id', $house_id)->find();
        if (!$house) {
            return 0;
        }
        $calendarPrice = (new self)->where('house_id', $house_id)->where('day_time', '>=', $startTime)->where('day_time', '<', $endTime)->select();
        $calendar = [];
        foreach ($calendarPrice as $item) {
            $calendar[$item['day_time']] = $item['price'];
        }
        $time = 24 * 60 * 60;
        $price = 0;
        //不等于离开日期
        for ($i = $startTime; $i < $endTime; $i += $time) {
            if (isset($calendar[$i])) {
                $price = bcadd($price, $calendar[$i], 2);
            } else {
                $price = bcadd($price, $house['price'], 2);
            }
        }
        return $price;
    }
}
